//
// Created by chen on 2023/6/24.
//
#include "account.h"

bool isFileExistAndNotEmpty(string fileName){
    ifstream ifs;
    ifs.open(fileName, ios::in);
    if(!ifs.is_open()){
        ifs.close();
        return false;  //文件不存在
    }
    char ch;
    ifs>>ch;
    if(ifs.eof()){
        ifs.close();
        return false;  // 文件为空
    }
    ifs.close();
    return true;
}

void Account::initStudentPasswd(){
    ifstream ifs;
    ifs.open(STUDENTFILE, ios::in);
    string buf;
    while (getline(ifs, buf)){   // 按行读取文件
        vector<string> temp;
        int start = 0;
        int pos = -1;
        while (true){
            pos = buf.find(",", start);
            if(pos == -1){
                break;
            }
            temp.push_back(buf.substr(start, pos-start));
            start = pos + 1;  // 因为此时pos指向,位置 故应该从pos+1开始找
        }
        map<string, string> tempMap;
        tempMap.insert(pair<string, string>(temp[1], temp[2]));
        this->studentPasswd.insert(pair<string, map<string, string>>(temp[0], tempMap));
    }
    ifs.close();
}

void Account::initTeacherPasswd(){
    ifstream ifs;
    ifs.open(TEACHERFILE, ios::in);
    string buf;
    while (getline(ifs, buf)){   // 按行读取文件
        vector<string> temp;
        int start = 0;
        int pos = -1;
        while (true){
            pos = buf.find(",", start);
            if(pos == -1){
                break;
            }
            temp.push_back(buf.substr(start, pos-start));
            start = pos + 1;  // 因为此时pos指向,位置 故应该从pos+1开始找
        }
        map<string, string> tempMap;
        tempMap.insert(pair<string, string>(temp[1], temp[2]));
        this->teacherPasswd.insert(pair<string, map<string, string>>(temp[0], tempMap));
    }
    ifs.close();
}

void Account::initManagerPasswd(){
    ifstream ifs;
    ifs.open(MANAGERFILE, ios::in);
    string buf;
    while (getline(ifs, buf)){   // 按行读取文件
        vector<string> temp;
        int start = 0;
        int pos = -1;
        while (true){
            pos = buf.find(",", start);
            if(pos == -1){
                break;
            }
            temp.push_back(buf.substr(start, pos-start));
            start = pos + 1;  // 因为此时pos指向,位置 故应该从pos+1开始找
        }
        this->managerPasswd.insert(pair<string, string>(temp[0], temp[1]));
    }
    ifs.close();
}

Account::Account() {
    bool isReadStudentFile = isFileExistAndNotEmpty(STUDENTFILE);
    if(isReadStudentFile){
        this->initStudentPasswd();
    }

    bool isReadTeacherFile = isFileExistAndNotEmpty(TEACHERFILE);
    if(isReadTeacherFile){
        this->initTeacherPasswd();
    }

    this->managerPasswd.insert(pair<string, string>("root", "toor"));   // 添加默认管理员账号
    bool isReadManagerFile = isFileExistAndNotEmpty(MANAGERFILE);
    if(isReadManagerFile){
        this->initManagerPasswd();
    }
}

Account::~Account() {

}

